#include<iostream>
#include<pthread.h>
#include<unistd.h>
#include<string>
using namespace std;

const int num=5;
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;
void* wait(void* args)
{
    string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&gmutex);//加锁或者互斥

        pthread_cond_wait(&gcond,&gmutex);//这里就是线程等待的位置；需要主线程一个一个的唤醒

        cout<<"I am "<<name<<endl;
        pthread_mutex_unlock(&gmutex);
        usleep(100000);
    }

}
int main()
{
    pthread_t threads[num];
    for(int i=0;i<num;i++)
    {
        char* name = new char[1024];
        snprintf(name,1024,"thread-%d",i+1);
        pthread_create(threads+i,nullptr,wait,(void*)name);
    }

    while(true)//主线程唤醒其他线程
    {
        pthread_cond_signal(&gcond);
        cout<<"唤醒一个线程"<<endl;
        sleep(2);
    }

    for(int i=0;i<num;i++)
    {
        pthread_join(threads[i],nullptr);
    }
    return 0;
}